package com.mfs.proxy.core.util;

import com.mfs.proxy.core.client.config.ClientConfig;
import com.mfs.proxy.core.server.config.ServerConfig;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程任务执行器
 * 根据客户端、服务端的配置创建线程池，执行代理任务
 * @author mfs
 * @date 2023/7/2 23:04
 **/
public class ProxyTaskExecutor {
    private static ProxyTaskExecutor instance = new ProxyTaskExecutor();
    private ExecutorService threadPool;

    private ProxyTaskExecutor(){
        if (isClient()) {
            threadPool = Executors.newFixedThreadPool(ClientConfig.getInstance().getConcurrentRequestNum());
        } else {
            threadPool = Executors.newFixedThreadPool(ServerConfig.getInstance().getConcurrentRequestNum());
        }
    }

    private boolean isClient() {
        try {
            Class.forName("com.mfs.proxy.client.ReverseProxyClient");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    public static ProxyTaskExecutor getInstance() {
        return instance;
    }

    public void execute(Runnable runnable) {
        threadPool.submit(runnable);
    }
}
